import { message } from "@/utils/message";
import { queryProduceExamList, getDistributionExamScores } from "@/api/exam";
import { type PaginationProps } from "@pureadmin/table";
import { FormItemProps } from "./types";
import { ref, computed, watch, type Ref, onMounted, reactive } from "vue";
import { useAppStoreHook } from "@/store/modules/app";
import {
  delay,
  useDark,
  useECharts,
  type EchartOptions
} from "@pureadmin/utils";

export function useForm() {
  const taskRef = ref();

  function setFormInlineToTsx(data?: FormItemProps) {
    taskRef.value = data;
  }

  const dataList = ref([]);
  const loading = ref(true);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "工作单位",
      prop: "employment",
      minWidth: 140
    },
    {
      label: "姓名",
      prop: "fullname",
      minWidth: 100
    },
    {
      label: "分数",
      prop: "score",
      minWidth: 100,
      formatter: row => {
        if (row.endtime != "") {
          return `${row.score}分`;
        } else {
          return "未交卷";
        }
      }
    },
    {
      label: "开考时间",
      prop: "starttime",
      minWidth: 140
    },
    {
      label: "交卷时间",
      prop: "endtime",
      minWidth: 140
    }
  ];

  async function onSearch() {
    queryProduceExamList({
      taskid: taskRef.value.id,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    }).then(res => {
      if (res.success) {
        console.log(JSON.stringify(res));
        dataList.value = res.data.list;
        pagination.total = res.data.total;
        loading.value = false;
      } else {
        message("查询数据异常:" + res.errMsg, { type: "error" });
      }
    });
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  /** 图形 */
  const { isDark } = useDark();

  const theme: EchartOptions["theme"] = computed(() => {
    return isDark.value ? "dark" : "light";
  });

  const pieChartRef = ref<HTMLDivElement | null>(null);
  const { setOptions, resize } = useECharts(
    pieChartRef as Ref<HTMLDivElement>,
    {
      theme
    }
  );

  async function onPieChart() {
    getDistributionExamScores({
      taskid: taskRef.value.id
    }).then(res => {
      if (res.success) {
        console.log(JSON.stringify(res));
        setOptions({
          tooltip: {
            trigger: "item"
          },
          legend: {
            icon: "circle",
            //@ts-expect-error
            right: true
          },
          series: [
            {
              name: "考生成绩分布",
              type: "pie",
              top: "25%",
              radius: "80%",
              center: ["40%", "50%"],
              color: ["#FF0000", "#FFA500", "#FFFF00", "#008000", "#0000FF"],
              data: res.data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)"
                }
              }
            }
          ]
        });
      }
    });
  }

  watch(
    () => useAppStoreHook().getSidebarStatus,
    () => {
      delay(600).then(() => resize());
    }
  );

  onMounted(() => {
    onSearch();
    onPieChart();
  });

  return {
    pieChartRef,
    setFormInlineToTsx,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
